package org.example.commerce.imp.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.example.commerce.api.beans.ModifyUserParam;
import org.example.commerce.api.beans.NewUserParam;
import org.example.commerce.dao.UserMapper;
import org.example.commerce.dao.entity.User;
import org.example.common.response.R;
import org.example.commerce.imp.service.UserService;
import org.example.common.enums.BusinessErrorCode;
import org.example.common.exception.BusinessException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public R<User> userLogin(HttpServletRequest request, String username , String password) {
        //1.查询用户是否存在
        Example example = new Example(User.class);
        example.createCriteria()
                .andLike("username", username);
        User loginUser = userMapper.selectOneByExample(example);

        if (loginUser == null) {
            return R.error("用户名不存在");
        }
        //2.校验用户密码
        if (!loginUser.getPassword().equals(password)) {
            return R.error("密码错误");
        }
        //3.检测账号状态
        if (loginUser.getStatus() == 0) {
            return R.error("用户已冻结");
        }
        //4.登录成功，将员工id存入Session
        request.getSession().setAttribute("user", loginUser.getId());
        return R.success(loginUser);
    }

    @Override
    public R<User> userSave(HttpServletRequest request, NewUserParam user) {
        if(user.getName()==null){
            return R.error("用户名不能为空");
        }
        if (selectUserByName(user.getName()) != null) {
            return R.error("用户已存在");
        }
        if(user.getUsername()==null){
            return R.error("账号不能为空");
        }
        if(user.getPassword()==null){
            return R.error("密码不能为空");
        }
        User newUser = User.builder()
                .identity("用户")
                .name(user.getName())
                .username(user.getUsername())
                .password(user.getPassword())
                .phoneNumber(user.getPhoneNumber())
                .sex(user.getSex().equals("男") ? "男" : "女")
                .status(1)
                .build();
        userMapper.insert(newUser);
        return R.success(newUser);
    }

    @Override
    public R<PageInfo<User>> users(Integer page, Integer pageSize) {
        //分页
        PageHelper.startPage(page, pageSize);
        List<User> Users = userMapper.selectAll();
        PageInfo<User> result = new PageInfo<>(Users);
        return R.success(result);
    }

    @Override
    public User selectUserByName(String name) {
        Example example = new Example(User.class);
        example.createCriteria()
                .andLike("name", "%" + name + "%");
        return userMapper.selectOneByExample(example);
    }

    @Override
    public R<String> deleteUserById(Long id) {
        if(id == 1){
            return R.error("管理员账号不可删除");
        }
        int i = userMapper.deleteByPrimaryKey(id);
        if (i == 0) {
            throw new BusinessException(BusinessErrorCode.USER_NOT_FOUND);
        }
        return R.success("删除成功");
    }

    @Override
    public R<User> modifyUser(ModifyUserParam nUser) {
        User oUser = userMapper.selectByPrimaryKey(nUser.getId());
        if (oUser==null){
            throw  new BusinessException(BusinessErrorCode.USER_NOT_FOUND);
        }
        BeanUtils.copyProperties(nUser, oUser);
        if(userMapper.updateByPrimaryKey(oUser)!=1){
            throw new BusinessException(BusinessErrorCode.UNKNOWN_ERROR);
        }
        return R.success(oUser);
    }

    @Override
    public User selectById(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        if (user==null){
            throw new BusinessException(BusinessErrorCode.USER_NOT_FOUND);
        }
        return user;
    }

    @Override
    public R<User> setUserStatus(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        if(user==null){
            throw new BusinessException(BusinessErrorCode.USER_NOT_FOUND);
        }
        user.setStatus(user.getStatus()==1 ? 0 : 1);
        userMapper.updateByPrimaryKey(user);
        return R.success(user);
    }


}
